package com.youlai.boot.modules.webapp.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.net.MalformedURLException;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 资源访问控制器
 */
@Slf4j
@RestController
@RequestMapping("/files")
@RequiredArgsConstructor
public class WebAppResourceController {

    /**
     * 访问上传的图片
     *
     * @param date 日期目录，例如 20240601
     * @param filename 文件名
     * @return 图片资源
     */
    @GetMapping("/upload/idphoto/{date}/{filename:.+}")
    public ResponseEntity<Resource> getIdPhoto(@PathVariable String date, @PathVariable String filename) {
        try {
            Path filePath = Paths.get(System.getProperty("user.dir") + "/upload/idphoto/" + date + "/" + filename);
            Resource resource = new UrlResource(filePath.toUri());
            
            if (resource.exists() && resource.isReadable()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + resource.getFilename() + "\"")
                        .contentType(MediaType.IMAGE_JPEG)
                        .body(resource);
            } else {
                log.error("文件不存在或不可读: {}", filePath);
                return ResponseEntity.notFound().build();
            }
        } catch (MalformedURLException e) {
            log.error("文件访问错误", e);
            return ResponseEntity.badRequest().build();
        }
    }
} 